<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Ad;
use App\Models\Admin\AdCate;
use App\Models\Admin\AdminMenu;
use App\Models\Admin\AdminRole;
use App\Models\Admin\AdminUser;
use App\Tools\Prstatic;
use Illuminate\Http\Request;

class SystemController extends BaseController
{

    /**
     * 用户权限
     */
    public function userList()
    {
        $params = $this->requestArr;
        $where = [];
        if ($params['username']) {
            $where['name'] = $params['name'];
        }
        if ($params['mobile']) {
            $where['mobile'] = $params['mobile'];
        }
        $where['store_id'] = 0;
        $list = AdminUser::where($where)->paginate(15);
        foreach ($list as $key => $item) {
            $list[$key]['roleName'] = AdminRole::where(['id' => $item['role_id']])->value('name');
        }
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        return view('admin/system/userList', ['data' => $list]);
    }

    // 添加，编辑后台用户
    public function userEdit()
    {
        $data = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if (empty($data['username'])) {
                errorMsg('请填写登录名');
            }
            if (empty($data['mobile'])) {
                errorMsg('请填写手机号');
            }
            if (empty($data['role_id'])) {
                errorMsg('请选择角色');
            }
            if (empty($data['id']) && empty($data['password'])) {
                errorMsg('请填写密码');
            }
            if ($data['id']) {
                $isZai = AdminUser::where([['username', '=', $data['username'], 'or'], ['mobile', '=', $data['mobile'], 'or']])->where('id', '!=', $data['id'])->value('id');
            } else {
                $isZai = AdminUser::where([['username', '=', $data['username'], 'or'], ['mobile', '=', $data['mobile'], 'or']])->value('id');
            }
            if ($isZai) {
                errorMsg('改用户名或手机号已被占用');
            }
            AdminUser::userEdit($data);
            successMsg();
        } else {
            $info = [];
            if ($data['id']) {
                $info['data'] = AdminUser::where(['id' => $data['id']])->first();
            }
            $info['roleList'] = AdminRole::where([])->get();
            return view('admin/system/userEdit', $info);
        }
    }

    // 添加，编辑后台用户
    public function userPassword()
    {
        $data = $this->requestArr;
        if ($this->requestMethod == 'POST') {
            if (empty($data['id']) && empty($data['password'])) {
                errorMsg('请填写密码');
            }
            if ($data['password'] != $data['password1']) {
                errorMsg('请再次输入密码不一致');
            }
            $safe = pbGetRandStr();
            $info['safe'] = $safe;
            $info['password'] = md5($data['password'] . $safe);
            AdminUser::where(['id' => $this->userArr['user_id']])->update($info);
            successMsg();
        } else {
            $info = [];
            if ($data['id']) {
                $info['data'] = AdminUser::where(['id' => $data['id']])->first();
            }
            return view('admin/system/userPassword', $info);
        }
    }

    // 删除登录员
    public function userDel()
    {
        $data = $this->requestArr;
        if ($data['id'] && $data['id'] > 1) {
            AdminUser::where(['id' => $data['id']])->delete();
            successMsg();
        }
        errorMsg();
    }

    // 角色列表
    public function roleList()
    {
        $params = $this->requestArr;
        $list = AdminRole::getList($params);
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        if (!empty($params['name'])) {
            $list->appends(['name' => $params['name']])->render();
        }
        return view('admin/system/roleList', ['data' => $list]);
    }

    public function roleAdd(Request $request)
    {
        // 页面权限检查
        $this->checkAuth($this->admin_role_list_id, $this->userArr['user_auth']);

        if ($request->isMethod('POST')) {
            $data['name'] = $this->requestArr['role_name'];
            $data['auth'] = $this->requestArr['auth'];
            $data['sort'] = $this->requestArr['sort'];
            $data['note'] = $this->requestArr['note'];
            if (empty($data['name'])) {
                showMsg(1002, '请输入角色名');
            }
            if ($data['sort'] < 1 || $data['sort'] > 99) {
                showMsg(103, '排序字段为1~99之间的数字');
            }

            $userInfo = AdminRole::getInfoByKey('name', $data['name']);
            if ($userInfo) {
                showMsg(1002, '角色名已存在');
            }

            // 权限
            $data['auth'] = json_encode(explode(',', $data['auth']), JSON_UNESCAPED_UNICODE);
            // 添加
            $is_user = AdminRole::addInfo($data);
            if ($is_user) {
                showMsg(1, '添加成功');
            }
            showMsg(1002, '参数错误~');
        }
        $dataArr = [];
        return view('admin/system/roleAdd', $dataArr);
    }

    public function roleEdit()
    {
        $id = $this->requestArr['id'];
        // 修改提交
        if ($this->requestMethod == "POST") {
            $data = $this->requestArr;
            if (!$data['name']) {
                errorMsg('请输入角色名');
            }
            if (!$data['auth']) {
                errorMsg('请输入权限');
            }
            //更新
            $is_user = AdminRole::upInfo($data);
            if ($is_user) {
                successMsg();
            }
            errorMsg();
        } else {
            if ($id) {
                $infoRole = AdminRole::getInfoById($id);
                $info['data'] = $infoRole;
                $info['menuList'] = AdminMenu::getTreeByMenu($infoRole['auth']);
            } else {
                $info['menuList'] = AdminMenu::getTreeByMenu();
            }
            return view('admin/system/roleEdit', $info);
        }
    }

    public function roleDel()
    {
        $id = $this->requestArr['id'];
        if ($id && $id > 1) {
            $isZai = AdminUser::where(['role_id' => $id])->value('id');
            if ($isZai) {
                errorMsg('该角色下还有用户在使用');
            }
            $res = AdminRole::deleteById($id);
            if ($res) {
                successMsg();
            }
        }
        errorMsg();
    }

    /**
     * 获取菜单列表
     */
    public function navList()
    {
        $list = AdminMenu::where(['pid' => 0, 'type' => 1])->orderBy('type')->orderBy('sort')->get()->toArray();
        foreach ($list as $key => $value) {
            $list[$key]['son'] = AdminMenu::where(['pid' => $value['id']])->orderBy('sort')->get()->toArray();
        }
        return view('admin/system/navList', ['data' => $list]);
    }

    /**
     * 添加菜单
     */
    public function navAdd()
    {
        if ($this->requestMethod == 'POST') {
            $info['pid'] = $this->requestArr['pid'];
            $info['name'] = $this->requestArr['cate_name'];
            $info['url'] = $this->requestArr['url'];
            $info['icon_font'] = $this->requestArr['icon_font'];
            $info['sort'] = $this->requestArr['sort'];
            $info['type'] = $this->requestArr['type'];
            if ($info['name'] && $info['url']) {
                $info = array_filter($info);
                AdminMenu::insertGetId($info);
                successMsg();
            }
        }
        errorMsg();
    }

    /**
     * 菜单删除
     */
    public function navDel()
    {
        $id = $this->requestArr['id'];
        AdminMenu::where(['id' => $id])->delete();
        successMsg();
    }

    /**
     * 添加菜单
     */
    public function navEdit()
    {
        if ($this->requestMethod == 'POST') {
            $id = $this->requestArr['id'];
            $ppa = $this->requestArr['ppa'];
            $val = $this->requestArr['ppv'];
            if ($id && $ppa && $val) {
                $info[$ppa] = $val;
                AdminMenu::where(['id' => $id])->update($info);
            }
            successMsg();
        }
        errorMsg();
    }

    /**
     * @Author   Afree
     * @DateTime 2020-04-29T11:27:02+0800
     * @return   [type]
     */
    public function adList()
    {
        $param = $this->requestArr;
        $list = Ad::getList($this->requestArr);

        // 搜索条件
        if (!empty($param['title'])) {
            $list->appends(['title' => $param['title']])->render();
        }
        // 状态
        $status = Prstatic::$status;
        foreach ($list as $k => $v) {
            $list[$k]['status'] = $status[$v['status']];
            // 详细信息
            $adCateInof = AdCate::getInfoById($v['cate_id'])->toArray();
            $list[$k]['cate_name'] = $adCateInof['name'];
        }
        return view('admin/system/adList', ['data' => $list, 'status' => $status, 'param' => $param]);
    }

    /**
     * 广告图添加修改
     * @param Request $request
     * @return
     */
    public function adEdit()
    {
        if ($this->requestMethod == 'POST') {
            $data = $this->requestArr;
            if (empty($data['title'])) {
                errorMsg('请填写标题');
            }
            if (empty($data['cate_id'])) {
                errorMsg('请填写分类');
            }
            if (empty($data['image'])) {
                errorMsg('请上传图片');
            }
            if ($data['id']) {
                //更新
                Ad::updateInfoById($data['id'], $data);
            } else {
                //添加
                Ad::addInfo($data);
            }
            successMsg();
        } else {
            $id = $this->requestArr['id'];
            if ($id) {
                $dataArr['data'] = Ad::getInfoById($id);
            }
            // 分类
            $dataArr['ad_cate'] = AdCate::getList([], 0);
            // 广告图列表
            $dataArr['status'] = Prstatic::$status;
            return view('admin/system/adEdit', $dataArr);
        }
    }

    /**
     * 删除广告图
     */
    public function adDel()
    {
        $id = $this->requestArr['id'];
        if ($id) {
            Ad::deleteById($id);
            successMsg();
        }
        errorMsg();
    }

    // Ad分类列表
    public function adCateList()
    {
        $list = AdCate::getList($this->requestArr);
        // 一般状态
        $status = Prstatic::$status;
        foreach ($list as $k => $v) {
            $list[$k]['status'] = $status[$v['status']]; // 状态
        }
        return view('admin/system/adCateList', ['data' => $list, 'status' => $status]);
    }

    /**
     * 广告分类添加
     * @param Request
     */
    public function adCateEdit()
    {
        if ($this->requestMethod == 'POST') {
            if (empty($this->requestArr['name'])) {
                errorMsg('分类名称必须填写');
            }
            if ($this->requestArr['id']) {
                $res = AdCate::updateInfoById($this->requestArr['id'], $this->requestArr);
            } else {
                $res = AdCate::addInfo($this->requestArr);
            }
            if ($res) {
                successMsg();
            }
            errorMsg();
        } else {
            if ($this->requestArr['id']) {
                $dataArr['data'] = AdCate::getInfoById($this->requestArr['id']);
            }
            $dataArr['status'] = Prstatic::$status;
            return view('admin/system/adCateEdit', $dataArr);
        }
    }

    /**
     * 删除广告分类
     */
    public function adCateDel()
    {
        $id = $this->requestArr['id'];
        if ($id > 0) {
            $num = Ad::where(['cate_id' => $id])->count();
            if ($num > 0) {
                errorMsg('该分类正在使用中，请删除所有使用此分类的广告后才可以删除此分类');
            }
            AdCate::deleteById($id);
            successMsg();
        }
        errorMsg();
    }
}
